<template>
    <div class="addDiv">
        <el-form ref="ruleFormRef" :model="ruleForm" label-width="120px" class="demo-ruleForm" size="default"
            status-icon :rules="rules">
            <el-form-item label="名称" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="活动类型" prop="type">
                <el-select v-model="ruleForm.type" placeholder="请选择">
                    <el-option :label="item.name" :value="item.name" v-for="(item, index) in title" :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item label="图片" prop="photo">
                <Uploads :row="ruleForm.photo" @OK="OKdata" @removeImg="removeImg"></Uploads>
            </el-form-item>
            <el-form-item label="活动时间" prop="activityTime">
                <div class="activityTime">
                    <el-date-picker v-model="ruleForm.activityTime" type="datetimerange" range-separator="To"
                        start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY/MM/DD hh:mm:ss"
                        value-format="YYYY-MM-DD hh:mm:ss" />
                </div>
            </el-form-item>
            <el-form-item label="活动地址" prop="address">
                <el-input v-model="ruleForm.address" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="报名人数" prop="peopleNum">
                <div style="display: flex; align-items: center;gap: 20px;">
                    <el-input v-model="ruleForm.peopleNum" placeholder="请输入" type="number"
                        oninput="if(value<-1)value=-1" />
                    <span style="color: red;">注意：如果人数为-1则表示不限人数，小程序展示为不限</span>
                </div>

            </el-form-item>
            <el-form-item label="状态" prop="status">
                <div>
                    <el-radio-group v-model="ruleForm.status" class="ml-4">
                        <el-radio label="立即上线" size="large" value="1"></el-radio>
                        <el-radio label="暂不上线" size="large" value="0"></el-radio>
                    </el-radio-group>
                    <div>
                        <span v-if="ruleForm.status == '1'" style="color: red;font-size: 12px;">上线后不允许更改信息</span>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="活动详情" prop="activityDetail">
                <Wangeditor @closeOK="closeOKDataActivityDetail" :row="ruleForm.activityDetail">
                </Wangeditor>
            </el-form-item>
            <el-form-item label="活动须知" prop="eventNotice">
                <Wangeditor @closeOK="closeOKDataEventNotice" :row="ruleForm.eventNotice">
                </Wangeditor>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确认
                </el-button>
                <el-button @click="closeAdd()">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
// 富文本
import Wangeditor from '@/components/wangeditor/index.vue'
import { onMounted, reactive, ref } from 'vue'
import { activityUpdate, activityAdd, activityAddType } from '@/api/activity.js'
import Uploads from '@/components/elUploads/index.vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router';
const route = useRoute();
const emit = defineEmits(['closeAdd', 'closeOK'])
const props = defineProps({
    isAdd: {
        type: Boolean,
        default: true, // 默认值为 true
    },
    row: {
        type: Object,
        default: () => ({}), // 默认值为一个空对象
    },
})
onMounted(() => {

    if (!props.isAdd) {
        ruleForm.name = props.row.name; // 初始化表单字段值
        ruleForm.type = props.row.type; // 初始化表单字段值
        ruleForm.photo = props.row.photo; // 初始化表单字段值
        ruleForm.activityTime = props.row.activityTime; // 初始化表单字段值
        ruleForm.address = props.row.address; // 初始化表单字段值
        if (props.row.peopleNum == '不限') {
            ruleForm.peopleNum = -1;
        } else {
            ruleForm.peopleNum = props.row.peopleNum; // 初始化表单字段值
        }
        // console.log(initRichText(props.row.activityDetail));

        ruleForm.activityDetail = props.row.activityDetail; // 初始化表单字段值
        // ruleForm.activityDetail = initRichText(props.row.activityDetail); // 初始化表单字段值
        ruleForm.eventNotice = props.row.eventNotice; // 初始化表单字段值
        ruleForm.status = props.row.status; // 初始化表单字段值
    }
    getTitleList()

})
// // 初始化处理
// const initRichText = (data) => {
//     // 1. 转换图片 data-src 为 src（关键：否则图片不显示）
//     let handledHtml = data.replace(
//         /<img([^>]*?)data-src="([^"]*?)"([^>]*?)>/gi,
//         '<img$1src="$2"$3>'  // 将 data-src 替换为 src
//     );

//     // 2. 移除隐藏的无用标签（如 <mp-style-type>）
//     handledHtml = handledHtml.replace(/<p style="display: none;">[\s\S]*?<\/p>/gi, '');

//     // 3. 格式化为 uni-richtext 要求的 nodes 结构（支持字符串直接传入，也可转数组）
//     return handledHtml
// }

const ruleFormRef = ref()
const ruleForm = reactive({
    name: '',
    type: '',
    photo: [],
    activityTime: [],
    address: '',
    activityDetail: '',
    eventNotice: '',
    peopleNum: '',
    status: '0',
})
const rules = reactive({
    name: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    type: [
        { required: true, message: '请选择', trigger: 'change' },
    ],
    photo: [
        { required: true, message: '请选择', trigger: 'change' },
    ],
    activityTime: [
        { required: true, message: '请选择', trigger: 'change' },
    ],
    status: [
        { required: true, message: '请选择', trigger: 'change' },
    ],
    address: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    activityDetail: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    peopleNum: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],

})
const title = reactive([])
const getTitleList = () => {
    title.length = 0
    activityAddType().then(res => {
        if (res.code == 200) {
            title.push(...res.data)
        }
    })
}
// 活动须知
const closeOKDataEventNotice = (data) => {
    ruleForm.eventNotice = data
}
// 活动详情
const closeOKDataActivityDetail = (data) => {
    ruleForm.activityDetail = data
}

// 图片上传
const OKdata = (url) => {
    console.log(url)
    ruleForm.photo.push(...url)
}
// 图片-删除
const removeImg = (item) => {
    ruleForm.photo = item

}

// 表格确认
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (props.isAdd) {
                if (ruleForm.peopleNum == -1) {
                    ruleForm.peopleNum = '不限'
                }

                activityAdd(ruleForm).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            type: 'success',
                            message: '添加成功',
                        })
                        emit('closeOK')
                    }
                })

            } else {
                if (ruleForm.peopleNum == -1) {
                    ruleForm.peopleNum = '不限'
                }
                activityUpdate({ ...ruleForm, id: props.row.id }).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            type: 'success',
                            message: '修改成功',
                        })
                        emit('closeOK')
                    }
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 关闭
const closeAdd = () => {
    emit('closeAdd')
}
</script>

<style lang="scss" scoped>
.addDiv {
    height: 750px;
    overflow-y: auto;
    position: relative;


    .activityTime {
        width: 500px;
    }

    ::v-deep .el-input {
        width: 200px;
    }

    ::v-deep .el-select {
        width: 200px;
    }
}
</style>